package com.gurun.camera.addDevice.util;

import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;

import com.danale.sdk.Danale;
import com.google.gson.Gson;
import com.gurun.camera.addDevice.entity.WifiInfoEntity;

/**
 * Created by Administrator on 2016/9/13.
 */
public class WifiCache {
    private static String CACHE_NAME = "wifi_cache";
    private static volatile WifiCache mInstance;

    private WifiCache(){};

    public static WifiCache getInstance(){
        if(mInstance == null){
            synchronized (WifiCache.class){
                if(mInstance == null){
                    mInstance = new WifiCache();
                }
            }
        }
        return mInstance;
    }

    /**
     * save wifi info
     * @param entity
     */
    public synchronized void saveWifiInfo(WifiInfoEntity entity){
        if(entity != null && !TextUtils.isEmpty(entity.getSsid()) && entity.getPassword() != null){
            SharedPreferences.Editor edit = Danale.get().getBuilder().getContext().getSharedPreferences(CACHE_NAME, Context.MODE_PRIVATE).edit();
            String json = new Gson().toJson(entity);
            edit.putString(entity.getSsid(),json);
            edit.apply();
        }
    }

    /**
     * obtain wifi info
     */
    public synchronized WifiInfoEntity getWifiInfo(String ssid){
        if(!TextUtils.isEmpty(ssid)){
            SharedPreferences sharedPreferences = Danale.get().getBuilder().getContext().getSharedPreferences(CACHE_NAME, Context.MODE_PRIVATE);
            String jsonStr = sharedPreferences.getString(ssid, "");
            try{
                WifiInfoEntity entity = new Gson().fromJson(jsonStr, WifiInfoEntity.class);
                return entity;
            }catch (Exception e){
                return null;
            }
        }else{
            return null;
        }
    }



}
